package com.sanben.common.util;


import com.sanben.common.constant.Constant;
import com.sanben.common.constant.RedisKey;
import com.sanben.common.enums.ErrorMessage;
import com.sanben.common.exception.ServiceException;
import com.sanben.common.web.entity.UserVO;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: cyh
 * @description: servlet工具类
 * @date: 2020/8/03 10:57
 */
public class ServletUtils {

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
         RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) attributes).getRequest();
    }

    /**
     * 获取请求头里的值
     */
    public static String getHeader(String name) {
        return getRequest().getHeader(name);
    }

    /**
     * 获取用户信息
     * @return
     */
    public static UserVO getUser() {
        UserVO user = (UserVO) SpringUtils.getBean(RedisUtil.class).get(RedisKey.USER_TOKEN + ServletUtils.getUserId());
        if (user == null) {
            throw new ServiceException(ErrorMessage.SYS_AUTO_ERROR.getMessage());
        }
        return user;
    }

    /**
     * 获取userId
     *
     * @return
     */
    public static String getUserId() {
        return getHeader(Constant.HTTP_HEADER_USER);
    }

    /**
     * 获取token
     *
     * @return
     */
    public static String getToken() {
        return getHeader(Constant.AUTHORIZATION);
    }
}
